package com.carol.lmsbe.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.carol.lmsbe.common.Result;
import com.carol.lmsbe.dto.*;
import com.carol.lmsbe.service.EquipmentBorrowService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

/**
 * 设备借用控制器
 */
@RestController
@RequestMapping("/api/equipment-borrow")
@RequiredArgsConstructor
@Slf4j
public class EquipmentBorrowController {

    private final EquipmentBorrowService equipmentBorrowService;

    /**
     * 分页查询设备借用记录
     */
    @GetMapping("/list")
    @PreAuthorize("hasAnyRole('ADMIN', 'LEADER', 'LAB_MANAGER')")
    public Result<Page<EquipmentBorrowDTO>> listBorrowRecords(EquipmentBorrowQueryRequest request) {
        try {
            Page<EquipmentBorrowDTO> result = equipmentBorrowService.listBorrowRecords(request);
            return Result.success(result);
        } catch (Exception e) {
            log.error("查询设备借用记录失败", e);
            return Result.error("查询设备借用记录失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取借用记录详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAnyRole('ADMIN', 'LEADER', 'LAB_MANAGER')")
    public Result<EquipmentBorrowDTO> getBorrowRecordById(@PathVariable Long id) {
        try {
            EquipmentBorrowDTO result = equipmentBorrowService.getBorrowRecordById(id);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取借用记录详情失败", e);
            return Result.error("获取借用记录详情失败: " + e.getMessage());
        }
    }

    /**
     * 申请借用设备
     */
    @PostMapping
    @PreAuthorize("hasAnyRole('ADMIN', 'LEADER', 'LAB_MANAGER')")
    public Result<EquipmentBorrowDTO> borrowEquipment(@Valid @RequestBody EquipmentBorrowRequest request) {
        try {
            EquipmentBorrowDTO result = equipmentBorrowService.borrowEquipment(request);
            return Result.success(result);
        } catch (Exception e) {
            log.error("申请借用设备失败", e);
            return Result.error("申请借用设备失败: " + e.getMessage());
        }
    }

    /**
     * 归还设备
     */
    @PostMapping("/return")
    @PreAuthorize("hasAnyRole('ADMIN', 'LEADER', 'LAB_MANAGER')")
    public Result<EquipmentBorrowDTO> returnEquipment(@Valid @RequestBody EquipmentBorrowReturnRequest request) {
        try {
            EquipmentBorrowDTO result = equipmentBorrowService.returnEquipment(request);
            return Result.success(result);
        } catch (Exception e) {
            log.error("归还设备失败", e);
            return Result.error("归还设备失败: " + e.getMessage());
        }
    }

    /**
     * 更新借用记录
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasAnyRole('ADMIN', 'LEADER')")
    public Result<EquipmentBorrowDTO> updateBorrowRecord(@PathVariable Long id, @Valid @RequestBody EquipmentBorrowUpdateRequest request) {
        try {
            request.setId(id);
            EquipmentBorrowDTO result = equipmentBorrowService.updateBorrowRecord(request);
            return Result.success(result);
        } catch (Exception e) {
            log.error("更新借用记录失败", e);
            return Result.error("更新借用记录失败: " + e.getMessage());
        }
    }

    /**
     * 删除借用记录
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAnyRole('ADMIN', 'LEADER')")
    public Result<Void> deleteBorrowRecord(@PathVariable Long id) {
        try {
            equipmentBorrowService.deleteBorrowRecord(id);
            return Result.success();
        } catch (Exception e) {
            log.error("删除借用记录失败", e);
            return Result.error("删除借用记录失败: " + e.getMessage());
        }
    }

    /**
     * 审批借用申请
     */
    @PostMapping("/{id}/approve-borrow")
    @PreAuthorize("hasAnyRole('ADMIN', 'LEADER')")
    public Result<EquipmentBorrowDTO> approveBorrowApplication(@PathVariable Long id, @Valid @RequestBody EquipmentBorrowApprovalRequest request) {
        try {
            request.setBorrowId(id);
            EquipmentBorrowDTO result = equipmentBorrowService.approveBorrowApplication(request);
            return Result.success(result);
        } catch (Exception e) {
            log.error("审批借用申请失败", e);
            return Result.error("审批借用申请失败: " + e.getMessage());
        }
    }

    /**
     * 审批归还申请
     */
    @PostMapping("/{id}/approve-return")
    @PreAuthorize("hasAnyRole('ADMIN', 'LEADER')")
    public Result<EquipmentBorrowDTO> approveReturnApplication(@PathVariable Long id, @Valid @RequestBody EquipmentBorrowReturnApprovalRequest request) {
        try {
            request.setBorrowId(id);
            EquipmentBorrowDTO result = equipmentBorrowService.approveReturnApplication(request);
            return Result.success(result);
        } catch (Exception e) {
            log.error("审批归还申请失败", e);
            return Result.error("审批归还申请失败: " + e.getMessage());
        }
    }

    /**
     * 获取我的借用记录
     */
    @GetMapping("/my-borrows")
    @PreAuthorize("hasAnyRole('ADMIN', 'LEADER', 'LAB_MANAGER')")
    public Result<Page<EquipmentBorrowDTO>> getMyBorrowRecords(EquipmentBorrowQueryRequest request) {
        try {
            Page<EquipmentBorrowDTO> result = equipmentBorrowService.getMyBorrowRecords(request);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取我的借用记录失败", e);
            return Result.error("获取我的借用记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取待审批借用申请
     */
    @GetMapping("/pending-borrows")
    @PreAuthorize("hasAnyRole('ADMIN', 'LEADER')")
    public Result<Page<EquipmentBorrowDTO>> getPendingBorrowApplications(EquipmentBorrowQueryRequest request) {
        try {
            Page<EquipmentBorrowDTO> result = equipmentBorrowService.getPendingBorrowApplications(request);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取待审批借用申请失败", e);
            return Result.error("获取待审批借用申请失败: " + e.getMessage());
        }
    }

    /**
     * 获取待审批归还申请
     */
    @GetMapping("/pending-returns")
    @PreAuthorize("hasAnyRole('ADMIN', 'LEADER')")
    public Result<Page<EquipmentBorrowDTO>> getPendingReturnApplications(EquipmentBorrowQueryRequest request) {
        try {
            Page<EquipmentBorrowDTO> result = equipmentBorrowService.getPendingReturnApplications(request);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取待审批归还申请失败", e);
            return Result.error("获取待审批归还申请失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除借用记录
     */
    @DeleteMapping("/batch")
    @PreAuthorize("hasAnyRole('ADMIN', 'LEADER')")
    public Result<Void> batchDeleteBorrowRecords(@RequestBody List<Long> ids) {
        try {
            equipmentBorrowService.batchDeleteBorrowRecords(ids);
            return Result.success();
        } catch (Exception e) {
            log.error("批量删除借用记录失败", e);
            return Result.error("批量删除借用记录失败: " + e.getMessage());
        }
    }

    /**
     * 导出借用数据
     */
    @GetMapping("/export")
    @PreAuthorize("hasAnyRole('ADMIN', 'LEADER')")
    public Result<byte[]> exportBorrowData(EquipmentBorrowQueryRequest request) {
        try {
            byte[] result = equipmentBorrowService.exportBorrowData(request);
            return Result.success(result);
        } catch (Exception e) {
            log.error("导出借用数据失败", e);
            return Result.error("导出借用数据失败: " + e.getMessage());
        }
    }
}
